<template>
  <div class="ce-cron-forecast">
    <el-table class="ce-cron-forecast__table" :data="forecasts" :border="true">
      <el-table-column type="index" label="次序" width="60" />
      <el-table-column prop="date" label="触发时间预报" />
    </el-table>
  </div>
</template>

<script>
export default {
  name: 'ceCronForecast'
}
</script>
<script setup>
import { defineExpose, defineProps, reactive, watch } from 'vue'
import dayjs from 'dayjs';
import cronParser from 'cron-parser'
import { ElMessage } from 'element-plus';

const props = defineProps({
  cronTime: {
    type: String,
    required: true,
  },
  num: {
    type: Number,
    default: 5,
  }
})

const forecasts = reactive([])

watch(props, () => update())

const update = async () => {
  forecasts.length = 0

  let interval
  try {
    interval = cronParser.parseExpression(props.cronTime)
  } catch (e) {
    ElMessage.error('触发时间格式有误，请检查并修改！')
    return
  }

  for(let _i = 0; _i < props.num; _i++) {
    forecasts.push({ date: dateFormat(interval.next()) })
  }
}

const dateFormat = (date) => dayjs(date).format('YYYY-MM-DD HH:mm:ss')

update()
defineExpose({update})
</script>

<style>
.ce-cron-forecast {
  margin-bottom: 16px;
  color: var(--el-text-color-regular);
  font-size: var(--el-font-size-base);
}

.ce-cron-forecast .el-table th.el-table__cell {
  color: var(--el-text-color-regular);
  font-weight: normal;
}
</style>